import { useEffect, useState, useContext } from "react";
import { templateContext, pageContext, onPreviewMessage } from "@/store/templateContext";

import { Dropdown, Menu, Button } from "@arco-design/web-react";
import { IconDragDotVertical, IconDelete } from "@arco-design/web-react/icon";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
import CreateComponents from "@/components/renderComponent/index";
import Drawer from "../editor/components/drawer";
import AddBlock from "./components/addBlock";
// function Template({ onChange }) {
//     const { dispatch } = useContext(templateContext);
//     function handleChangeTemplate(item) {
//         dispatch({ type: "setTemplate", data: item.name });
//         dispatch({ type: "setGlobal", data: item.global });
//         onChange();
//     }

//     const [list, setList] = useState([]);
//     useEffect(() => {
//         fetch("http://localhost:3030/api/template/all", {
//             method: "get",
//             headers: {
//                 "Content-Type": "application/json"
//             }
//         })
//             .then((data) => data.json())
//             .then(({ data }) => {
//                 setList(data);
//             });
//     }, []);
//     return (
//         <div className="p-3">
//             <div className="flex flex-col gap-3">
//                 {list.map((item, index) => (
//                     <div key={index} className="p-3 border cursor-pointer  border-gray-100 border-solid" onClick={() => handleChangeTemplate(item)}>
//                         {item.name}
//                     </div>
//                 ))}
//             </div>
//         </div>
//     );
// }

// function Sections({ template, onChange }) {
//     const [list, setList] = useState([]);

//     useEffect(() => {
//         fetch(`http://localhost:3030/api/template/sections/all?name=${template}`, {
//             method: "get",
//             headers: {
//                 "Content-Type": "application/json"
//             }
//         })
//             .then((data) => data.json())
//             .then(({ data }) => {
//                 setList(
//                     Object.keys(data).map((key) => {
//                         return {
//                             id: key,
//                             ...data[key]
//                         };
//                     })
//                 );
//             });
//     }, []);
//     return (
//         <div className="p-3">
//             <div className="flex flex-col gap-3">
//                 {list.map((item, index) => (
//                     <div key={index} className="p-3 border cursor-pointer  border-gray-100 border-solid" onClick={() => onChange(item)}>
//                         {item.name.zh_CN}
//                     </div>
//                 ))}
//             </div>
//         </div>
//     );
// }

// 积木块的block
function Blocks({ value, onChange }) {
    const { state, dispatch } = useContext(templateContext);

    function blockChange(value) {
        dispatch({ type: "addBlock", data: value });
        dispatch({ type: "previewPostMessage" });
    }
    return (
        <div className="flex flex-col gap-2 px-2">
            {value.map((el, index) => (
                <div key={index} onClick={() => onChange(index)} className="flex p-2 justify-between bg-gray-200 cursor-pointer rounded">
                    <span>{el.name.zh_CN}</span>
                    <span
                        className="text-red-500"
                        onClick={(e) => {
                            e.stopPropagation();
                            dispatch({ type: "delBlock", data: index });
                            dispatch({ type: "previewPostMessage" });
                        }}>
                        删除
                    </span>
                </div>
            ))}
            {state.blockOptions.length > 0 && (
                <Dropdown
                    droplist={
                        <Menu className="w-[200px]" onClickMenuItem={blockChange}>
                            {state.blockOptions.map((item, index) => (
                                <Menu.Item key={item.type}>{item.name.zh_CN}</Menu.Item>
                            ))}
                        </Menu>
                    }
                    position="bl"
                    trigger="click">
                    <Button type="primary">添加内容</Button>
                </Dropdown>
            )}
        </div>
    );
}

function Sections({onChange}) {
    const { state, dispatch: pageDispatch } = useContext(pageContext);
    const { dispatch } = useContext(templateContext);
    function onDragEnd(result) {
        const source = result.source.index;
        const destination = result.destination.index;
        pageDispatch({ type: "sort", source, destination });
    }
    return (
        <DragDropContext onDragEnd={onDragEnd}>
            <Droppable droppableId="list" isDragDisabled={false}>
                {(provided, snapshot) => (
                    <div ref={provided.innerRef} {...provided.droppableProps}>
                        {state.map((item, index) => (
                            <Draggable key={item.id} draggableId={`item-${item.id}`} index={index}>
                                {(provided, snapshot) => (
                                    <div
                                        ref={provided.innerRef}
                                        {...provided.draggableProps}
                                        onClick={() => onChange(item)}
                                        className="p-3 mt-3 bg-gray-100 cursor-pointer flex justify-between  ">
                                        <span>
                                            {item.template}_{item.name}
                                        </span>

                                        <div className="flex gap-2 items-center">
                                            <IconDelete
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    pageDispatch({ type: "delPageBlockDrag", data: index });
                                                }}
                                            />
                                            <span {...provided.dragHandleProps}>
                                                <IconDragDotVertical />
                                            </span>
                                        </div>
                                    </div>
                                )}
                            </Draggable>
                        ))}
                        {provided.placeholder}
                    </div>
                )}
            </Droppable>
        </DragDropContext>
    );
}

// 页面积木块
function Page({ onAdd, onChange }) {
    // function onCreateTemplate() {
    //     fetch("http://localhost:3030/api/create/template", {
    //         method: "post",
    //         headers: {
    //             "Content-Type": "application/json"
    //         },
    //         body: JSON.stringify(state)
    //     });
    // }

    return (
        <div className="flex flex-col p-3 gap-3">
            <Sections onChange={onChange}/>
            <AddBlock onChange={onAdd} />
            {/* <Button type="primary" onClick={onAdd}>
                添加积木
            </Button>
            <Button type="primary" onClick={onCreateTemplate}>
                生成模版
            </Button> */}
        </div>
    );
}

function BlockGenerateImage() {
    const { state } = useContext(templateContext);
    function handleImage() {
        onPreviewMessage(state, "image");
    }
    return (
        <Button className="w-full" type="primary" onClick={handleImage}>
            生成图片
        </Button>
    );
}

export default function ({ onChange }) {
    const [current, setCurrent] = useState("page");

    const { state, dispatch } = useContext(templateContext);
    const { dispatch: pageDispatch } = useContext(pageContext);

    return (
        <div className="relative overflow-hidden w-full h-full">
            <Drawer header="页面" visible={current === "page"}>
                <Page
                    onAdd={() => {
                        setCurrent("setting");
                    }}
                    onChange={(item) => {
                        dispatch({ type: "updateTemplateStore", data: item });
                        setCurrent("setting");
                    }}
                />
            </Drawer>
            {/* 
            <Drawer header="所有模版" isBack={true} onBack={() => setCurrent("page")} visible={current === "template"}>
                <Template
                    onChange={() => {
                        setCurrent("sections");
                    }}
                />
            </Drawer>

            <Drawer
                header={`${state.template}模版`}
                onBack={() => {
                    setCurrent("template");
                }}
                isBack={true}
                visible={current === "sections"}>
                <Sections
                    template={state.template}
                    onChange={(item) => {
                        setCurrent("setting");
                        dispatch({ type: "setCurrentSection", data: item });
                        dispatch({ type: "previewPostMessage" });
                    }}
                />
            </Drawer> */}

            <Drawer
                header={`${state.template}_${state.name}积木块`}
                onBack={() => {
                    setCurrent("page");
                    pageDispatch({ type: "addPageBlock", data: state });
                }}
                isBack={true}
                footer={<BlockGenerateImage />}
                visible={current === "setting"}>
                <div className="p-2">
                    <CreateComponents
                        components={state.settings}
                        onChange={(item, index, value) => {
                            dispatch({ type: "updateSettings", index, value });
                            dispatch({ type: "previewPostMessage" });
                        }}
                    />
                    <Blocks
                        value={state.blocks}
                        onChange={(index) => {
                            setCurrent("block");
                            dispatch({ type: "setCurrentBlockIndex", data: index });
                        }}
                    />
                </div>
            </Drawer>

            <Drawer
                header={`${state.template}_${state.name}_块设置`}
                onBack={() => setCurrent("setting")}
                isBack={true}
                visible={current === "block"}>
                <div className="p-2">
                    {state.currentBlockIndex !== -1 && (
                        <CreateComponents
                            components={state.blocks[state.currentBlockIndex].settings}
                            onChange={(item, index, value) => {
                                dispatch({ type: "updateCurrentBlockIndex", index, value });
                                dispatch({ type: "previewPostMessage" });
                            }}
                        />
                    )}
                </div>
            </Drawer>
        </div>
    );
}
